package com.balabala.netty.myclient;

import com.balabala.netty.myclient.handler.ClientMessageHandler;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

import java.util.Scanner;

public class NettyClientMain {

    private final String ip;

    private final int port;

    public NettyClientMain(String ip, int port) {
        this.ip = ip;
        this.port = port;
    }

    /**
     * 初始化客户
     */
    private void init() throws Exception {
        //创建监听事件的监听器
        EventLoopGroup work = new NioEventLoopGroup();
        try {
            Bootstrap boot = new Bootstrap();
            boot.group(work);
            boot.channel(NioSocketChannel.class);
            boot.handler(new ChannelInitializer<NioSocketChannel>() {

                @Override
                protected void initChannel(NioSocketChannel ch) {
                    ChannelPipeline pipeline = ch.pipeline();
                    pipeline.addLast("encoder", new StringEncoder());
                    pipeline.addLast("decoder", new StringDecoder());
                    pipeline.addLast(new ClientMessageHandler());

                }
            });

            ChannelFuture channelFuture = boot.connect(ip, port).sync();
            channelFuture.addListener(future -> {
                if (future.isSuccess()) {
                    System.out.println("客户端启动中...");
                }
                if (future.isDone()) {
                    System.out.println("客户端启动成功...OK！");
                }
            });
            System.out.println(channelFuture.channel().localAddress().toString());
            /*
              这里用控制台输入数据
             */
            Channel channel = channelFuture.channel();
            //获取channel
            Scanner scanner = new Scanner(System.in);
            while (scanner.hasNextLine()) {
                String str = scanner.nextLine();
                channel.writeAndFlush(str + "\n");
            }
            channelFuture.channel().closeFuture().sync();
            scanner.close();
        } finally {
            work.shutdownGracefully();
        }
    }

    /**
     * 主方法入口
     *
     * @param args 入口参数
     * @throws Exception 异常
     */
    public static void main(String[] args) throws Exception {

        new NettyClientMain("127.0.0.1", 9090).init();
    }

}

